#include "page2_chuan.h"
#include "ui_page2_chuan.h"

page2::page2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::page2)
{
    ui->setupUi(this);
    this->setFixedSize(1280,720);

//################################################
//#                                              #
//#           设置界面2背景                        #
//#           最后一次修改4.9，11：16               #
//#                                              #
//################################################
    QPixmap widget_background = QPixmap(":/ocean.jpg");
    widget_background = widget_background.scaled(1280,720,Qt::KeepAspectRatio);
    QPixmap temp_background(widget_background.size());
    temp_background.fill(Qt::transparent);
    //白色透明度
    //    QPainter picture_background(&temp_background);
    //    picture_background.setCompositionMode(QPainter::CompositionMode_Source);
    //    picture_background.drawPixmap(0,0,widget_background);
    //    picture_background.setCompositionMode(QPainter::CompositionMode_DestinationIn);

    //    picture_background.fillRect(widget_background.rect(),QColor(0,0,0,150));
    //    picture_background.end();

    //    widget_background = temp_background;
    //黑色透明度
    QPainter picture_background(&widget_background);
    picture_background.setCompositionMode(QPainter::CompositionMode_Source);
    picture_background.drawPixmap(0,0,widget_background);
    picture_background.setCompositionMode(QPainter::CompositionMode_DestinationIn);

    picture_background.fillRect(widget_background.rect(),QColor(0,0,0,150));
    picture_background.end();

    ui->label_background->setPixmap(widget_background);

//################################################
//#                                              #
//#           串口通信初始化                       #
//#           最后一次修改4.9，19：52               #
//#                                              #
//################################################
    serial=new QSerialPort;
//串口配置初始化
    PortConfigure_Init();
    serialPort_Find();
//信号与槽
    connect(ui->Open_Port_Button,&QPushButton::clicked,this,&page2::serialPort_Open);
    connect(ui->Send_Data_Button,&QPushButton::clicked,this,&page2::Data_Send);
    connect(ui->Data_Send_LineEdit,&QLineEdit::returnPressed,this,&page2::Data_Send);
    connect(ui->Clear_Receive_TextBrowser_Button,&QPushButton::clicked,this,&page2::Receive_Part_Clear);
    connect(ui->Save_To_Document_Button,&QPushButton::clicked,this,&page2::Save);
    connect(ui->Load_From_Document_Button,&QPushButton::clicked,this,&page2::Load);
    connect(ui->Exit_Button,&QPushButton::clicked,this,&page2::Exit);
//set label style
    ui->label_1->setStyleSheet("color:rgb(255,255,255);");
    ui->label_2->setStyleSheet("color:rgb(255,255,255);");
    ui->label_3->setStyleSheet("color:rgb(255,255,255);");
    ui->label_4->setStyleSheet("color:rgb(255,255,255);");
    ui->label_5->setStyleSheet("color:rgb(255,255,255);");
    ui->label_6->setStyleSheet("color:rgb(255,255,255);");
    ui->label_7->setStyleSheet("color:rgb(255,255,255);");
    ui->label_8->setStyleSheet("color:rgb(255,255,255);");
    ui->label_9->setStyleSheet("color:rgb(255,255,255);");
    ui->label_10->setStyleSheet("color:rgb(255,255,255);");
    ui->Receive_ASCII_CheckBox->setStyleSheet("color:rgb(255,255,255);");
    ui->Receive_HEX_CheckBox->setStyleSheet("color:rgb(255,255,255);");
    ui->Send_ASCII_CheckBox->setStyleSheet("color:rgb(255,255,255);");
    ui->Send_HEX_CheckBox->setStyleSheet("color:rgb(255,255,255);");
}

page2::~page2()
{
    delete ui;
}

//################################################
//#                                              #
//#           窗口切换相关函数                      #
//#           最后一次修改4.9，7：51                #
//#                                              #
//################################################
void page2::on_pushButton_page1_clicked()
{
    emit pushbutton_page1_clicked();
}


void page2::on_pushButton_page2_clicked()
{
    emit pushbutton_page2_clicked();
}


void page2::on_pushButton_page3_clicked()
{
    emit pushbutton_page3_clicked();
}


void page2::on_pushButton_page4_clicked()
{
    emit pushbutton_page4_clicked();
}


//################################################
//#                                              #
//#           串口通信相关函数                      #
//#           最后一次修改4.9，19：52               #
//#                                              #
//################################################

void page2::serialPort_Find()
{
    ui->Port_ComboBox->clear();

    const auto infos=QSerialPortInfo::availablePorts();

    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->Port_ComboBox->addItem(info.portName());
            qDebug()<<info.portName();
            serial.close();
        }
    }

}
void page2::PortConfigure_Init()
{
    //波特率
    ui->Baud_rate_ComboBox->addItem("115200");
    ui->Baud_rate_ComboBox->addItem("38400");
    ui->Baud_rate_ComboBox->addItem("19200");
    ui->Baud_rate_ComboBox->addItem("9600");

    //校验位
    ui->Check_bit_ComboBox->addItem("0");

    //数据位
    ui->Data_bit_ComboBox->addItem("8");
    ui->Data_bit_ComboBox->addItem("7");

    //停止位
    ui->Stop_bit_ComboBox->addItem("2");
    ui->Stop_bit_ComboBox->addItem("1");

}
bool page2::serialPort_Open()
{
    //设置界面
    if(Port_Open==true)
    {
        ui->Port_ComboBox->setEnabled(true);
        ui->Data_bit_ComboBox->setEnabled(true);
        ui->Check_bit_ComboBox->setEnabled(true);
        ui->Stop_bit_ComboBox->setEnabled(true);
        ui->Baud_rate_ComboBox->setEnabled(true);
        ui->Open_Port_Button->setText("打开串口");
        serialPort_Close();
        return false;
    }

    //设置串口名字
    serial->setPortName(ui->Port_ComboBox->currentText());

    //检测串口是否能打开
    if(!serial->open(QIODevice::ReadWrite))
    {
        QErrorMessage *dialog=new QErrorMessage(this);
        dialog->setWindowTitle("错误");
        dialog->showMessage("未能打开串口！\n");
        dialog->showMessage("open fail，error info: "+serial->errorString());
        return false;
    }

    //设置波特率
    serial->setBaudRate(ui->Baud_rate_ComboBox->currentData().toInt());
    //设置校验位
    switch(ui->Check_bit_ComboBox->currentText().toInt())
    {
        case 0:
            serial->setParity(QSerialPort::NoParity);
            break;
        default:
            break;
    }
    //设置停止位
    switch(ui->Stop_bit_ComboBox->currentText().toInt())
    {
        case 2:
            serial->setStopBits(QSerialPort::TwoStop);
            break;
        case 1:
            serial->setStopBits(QSerialPort::OneStop);
            break;
        default:
            break;
    }
    //设置数据位置
    switch(ui->Data_bit_ComboBox->currentText().toInt())
    {
        case 8:
            serial->setDataBits(QSerialPort::Data8);
            break;
        case 7:
            serial->setDataBits(QSerialPort::Data7);
            break;
    }

    //设置流控制
    serial->setFlowControl(QSerialPort::NoFlowControl);//无流控制

    //设置槽函数
    connect(serial,&QSerialPort::readyRead,this,&page2::Data_Read);

    //界面内容刷新
    ui->Port_ComboBox->setEnabled(false);
    ui->Data_bit_ComboBox->setEnabled(false);
    ui->Check_bit_ComboBox->setEnabled(false);
    ui->Stop_bit_ComboBox->setEnabled(false);
    ui->Baud_rate_ComboBox->setEnabled(false);
    ui->Open_Port_Button->setText("关闭串口");//启动之后要改一下
    ui->Receive_TextBrowser->clear();
    ui->Send_TextBrowser->setEnabled(true);
    Port_Open=true;

    return true;
}
void page2::serialPort_Close()
{
    serial->clear();
    serial->close();
    Port_Open=false;
}

//原data_read
void page2::Data_Read()
{
    QByteArray data=serial->readAll();
    if(data.isEmpty())
    {
        qDebug()<<"failed...";
        return;
    }
    if(ui->Receive_ASCII_CheckBox->isChecked())
    {
        QString myStrTemp=QString::fromLocal8Bit(data);
        qDebug()<<"received: "<<myStrTemp;
        ui->Receive_TextBrowser->append(myStrTemp);
        ui->Receive_TextBrowser->append("\r\n");
        data.clear();
    }
    else
    {
        QDataStream out(&data,QIODevice::ReadOnly);
        while(!out.atEnd())
        {
            qint8 outChar=0;
            out>>outChar;
            QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));

            ui->Receive_TextBrowser->insertPlainText(str.toUpper());
            ui->Receive_TextBrowser->insertPlainText(" ");
            ui->Receive_TextBrowser->moveCursor(QTextCursor::End);
        }
        ui->Receive_TextBrowser->append("\r\n");
    }
}
/*
//进行解码的data_read()
void page2::Data_Read(){
    QByteArray data=serial->readAll();;
    //    debug看回信
            int size = data.size();
            for(int i = 0; i<size ;i++){
                qDebug()<<"debug : data["<<i<<"] = "<<(unsigned char)data.at(i);
            }
            qDebug()<<"\n";
//验证data是不是有数据，验证data的数据头
    if(data.isEmpty()){
        qDebug()<<"failed...ID:1..";
        return;
    }else if((unsigned char)data.at(0)!=0xFE){
        qDebug()<<"failed...ID:2.. : "<<(unsigned char)data.at(0)<<"\n";
        return;
    }
//进行异或数据校验位置
    unsigned char length = data.at(2);
    unsigned char jiaoyan = data.at(1);
    for(int i = 2;i <= (int)length + 2;i++)    {
        jiaoyan = jiaoyan ^ data.at(i);
    }
    if(jiaoyan != (unsigned char)data.at((int)length + 3)){
        qDebug()<<"校验未通过....\n";
        return;
    }
//数据解码
    //使用Data_upup的类指针
    //由于电控没有确定通讯的传输组，所以接收数据并反馈暂时无法完成
}
*/
void page2::Data_Send()
{
    QString str=ui->Data_Send_LineEdit->text();
    ui->Send_TextBrowser->append(str);
    ui->Send_TextBrowser->append("\n");
    int len=str.length();
    QByteArray data;//发送的数据
    if(ui->Send_HEX_CheckBox->isChecked())
    {
        if(len%2==1)
        {
            str=str.insert(len-1,'0');
        }
        String2Hex(str,data);
        serialPort_Send(data);
    }
    else
    {
        data=str.toLocal8Bit();
        qDebug()<<data;
        serialPort_Send(data);

    }
    ui->Data_Send_LineEdit->clear();
}

void page2::Data_Send_upup(QByteArray data_send)
{
        //debug
        int size = data_send.size();
        for(int i = 0; i<size ;i++){
            qDebug()<<"debug_send_upup : data["<<i<<"] = "<<(unsigned char)data_send.at(i);
        }
        qDebug()<<"\n";
    serial->write(data_send);
    qDebug()<<"send correct!\n";
}

void page2::serialPort_Send(const char *data)
{
    serial->write(data);
    qDebug()<<"send: "<<data<<Qt::endl;
}
void page2::String2Hex(QString str, QByteArray &data)
{
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    data.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        hstr=str[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
        lstr = str[i].toLatin1();
        hexdata = convertHexChart(hstr);
        lowhexdata = convertHexChart(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata*16+lowhexdata;
        i++;
        data[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    data.resize(hexdatalen);
}
char page2::convertHexChart(char ch)
{
    if((ch >= '0') && (ch <= '9'))
        return ch-0x30;  // 0x30 对应 ‘0’
    else if((ch >= 'A') && (ch <= 'F'))
        return ch-'A'+10;
    else if((ch >= 'a') && (ch <= 'f'))
        return ch-'a'+10;
    else
        return ch-ch;//不在0-f范围内的会发送成0
}

void page2::Receive_Part_Clear()
{
    ui->Receive_TextBrowser->clear();
}
void page2::Save()
{

}
void page2::Load()
{

}
void page2::Exit()
{
    exit(0);
}

